import { addProblemBank, lookProblemBank, updateProblemBank, deleteProblemBank, lookAllProblemBank } from '@/api/problemBank'

import store from '@/store'

const getDefaultState = () => {
  return {
    bankList: [],
  }
}

const state = getDefaultState()

const mutations = {
  SET_LIST: (state, value) => {
    state.bankList = value
  },
}

const actions = {
  // 条件查询
  async lookAllProblemBank({ commit, state }) {
    // 缓存
    if (state.bankList.length > 0) {
      resolve(state.bankList)
      return
    }
    return new Promise((resolve, reject) => {
      lookAllProblemBank()
        .then((response) => {
          commit('SET_LIST', response)
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 条件查询
  async lookProblemBank({ state }, problemBank) {
    return new Promise((resolve, reject) => {
      lookProblemBank(problemBank)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 添加一条题库
  async addProblemBank({ commit, state }, problemBank) {
    store.dispatch('problemBank/resetList')
    return new Promise((resolve, reject) => {
      addProblemBank(problemBank)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 修改题库
  async updateProblemBank({ commit, state }, problemBank) {
    store.dispatch('problemBank/resetList')
    return new Promise((resolve, reject) => {
      updateProblemBank(problemBank)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 批量删除题库
  async deleteProblemBank({ commit, state }, ids) {
    store.dispatch('problemBank/resetList')
    return new Promise((resolve, reject) => {
      deleteProblemBank(ids)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 重置列表
  async resetList({ commit, state }) {
    // 置空
    if (state.bankList.length > 0) {
      commit('SET_LIST', [])
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
